<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Remark: 网盘专用
 */
namespace app\api\controller;
use think\Db;
class Notice extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json_encode(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json_encode(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }
    /**
     * 同行同院(todo)
     */
    public function sameType()
    {
        extract(input());

        $time = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->value('user_time');
        return json(['status'=>200,'msg'=>$have]);
    }
    /**
     * 企业消息——拜访：医生专用
     * v_type：1是音频 2是视频 3是线下
     * v_status：1是未开始  2是进行中  3是已结束（暂时用不到）
     * v_take_status：1是待同意  2是同意  3是拒绝
     * read：1是未读  2是已读
     */
    public function visitNews()
    {
        extract(input());
        if(!isset($type) || !$type){
            $type = 1;
        }
        if($type == 1){
            $field = 'v_id n_id,v_id,v_type,v_start,v_end,v_day,v_week,v_take_status,v_take_read haveread,v_take_read,v_time,v_update';
            $field .= ',v_status,v_ask_status,v_address,v_remark,v_take_hold';
            $where = [
                'v_take_uid' => $user_id,
                'v_del_uids' => ['not like',"%,$user_id,%"]
            ];
        }else{
            $field = 'v_id,v_type,v_start,v_end,v_day,v_week,v_ask_status,v_ask_read,v_ask_read haveread,v_time,v_update';
            $field .= ',v_status,v_address,v_remark,v_ask_hold';
            $where = [
                'v_ask_uid' => $user_id,
                'v_del_uids' => ['not like',"%,$user_id,%"]
            ];
        }
        //只能查备注，拜访没有标题-------------！！！！！！！！！！！！！！！！
        if(isset($keyword) && $keyword){
            $where['v_remark'] = ['like',"%$keyword%"];
        }
        $data = Db::table('up_visit')
            ->where($where)
            ->order('v_update desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                if($type == 1 && $v['v_take_read'] == 1){
                    Db::table('up_visit')->where('v_id', $v['v_id'])->setField('v_take_read',2);
                }
                if($type == 2 && $v['v_ask_read'] == 1){
                    Db::table('up_visit')->where('v_id', $v['v_id'])->setField('v_ask_read',2);
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 企业消息——提问：医生和业务员通用
     * page
     * dq_zhuan:1未转  已转
     * 对于医生：user_username代表的是业务员的名字
     * 对于业务员：
     *     1、dqr_show为1的情况下代表的是正常的交流
     *          user_type为1时代表的是医生的回复
     *          user_type为2时代表的是其他业务员的回复（因为有可能转给其他同事了）
     *     2、dqr_show为2的情况下代表的是医生第一次发布
     */
    public function questionNews()
    {
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        $field = 'dqr_id n_id,dqr_id,dqr_dq_id,dqr_content,dqr_imgs,dqr_time,dq_zhuan,dq_zhuan_uid,dqr_read_uid,dqr_show';
        if($user_type == 1){
            $where = [
                'dq_send_uid' => $user_id,
                'dqr_user_id' => ['<>',$user_id],
                'dqr_show' => 1,
                'dqr_del_uid' => ['not like',"%,$user_id,%"]
            ];
            $field .= ',u2.user_username,dq_cpd_id,cpd_name';
        }else{
            $where = [
                'dq_all_uid' => ['like',"%,$user_id,%"],
                'dqr_user_id' => ['<>',$user_id],
                'dqr_del_uid' => ['not like',"%,$user_id,%"]
            ];
            $field .= ',u1.user_username doctor_name,u2.user_username,u2.user_type,dq_cpd_id,cpd_name';
        }
        //只搜资料名称
        if(isset($keyword) && $keyword){
            $where['cpd_name'] = ['like',"%$keyword%"];
        }
        $data = Db::table('up_company_pd_question dq')
            ->join('up_company_pd_question_reply dqr','dq.dq_id=dqr.dqr_dq_id','LEFT')
            ->join('up_u_user u1','dq.dq_send_uid=u1.user_id','LEFT')
            ->join('up_u_user u2','dqr.dqr_user_id=u2.user_id','LEFT')
            ->join('up_company_product_data cpd','dq.dq_cpd_id=cpd.cpd_id','LEFT')
            ->where($where)
            ->order('dqr_time desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($data){
            $data = $this->foreachStrArr($data,'dqr_imgs','dqr_read_uid',$user_id,'up_company_pd_question_reply','dqr_id','dq_zhuan_uid');
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 企业消息——SAE：医生和业务员通用
     * page
     * 对于医生：user_username代表的是回复的业务员的名字
     * 对于业务员：
     *     1、sr_show为1的情况下代表的是正常的交流
     *          user_type为1时代表的是医生的回复
     *          user_type为2时代表的是其他业务员的回复（因为有可能转给其他同事了）
     *     2、sr_show为2的情况下代表的是医生第一次发布
     *     3、sr_show为3的情况下代表的是医生有补充
     */
    public function saeNews()
    {
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        $field = 'sr_id n_id,sr_id,sr_sae_id,sae_name,sae_zhuan,sae_zhuan_ids,sr_content,sr_imgs,sr_time,sr_read_uid,sr_show';
        if($user_type == 1){
            $where = [
                'sae_send_uid' => $user_id,
                'sr_user_id' => ['<>',$user_id],
                'sr_show' => 1,
                'sr_del_uid' => ['not like',"%,$user_id,%"]
            ];
            $field .= ',u2.user_username,cp_name';
        }else{
            $where = [
                'sae_get_uid' => ['>',0],//业务员的话不需要看自己发布的
                'sae_all_ids' => ['like',"%,$user_id,%"],
                'sr_user_id' => ['<>',$user_id],
                'sr_del_uid' => ['not like',"%,$user_id,%"]
            ];
            $field .= ',u1.user_username doctor_name,u2.user_username,u2.user_type,cp_name';
        }
        //只搜报告名称
        if(isset($keyword) && $keyword){
            $where['sae_name'] = ['like',"%$keyword%"];
        }
        $data = Db::table('up_sae sae')
            ->join('up_sae_reply sr','sae.sae_id=sr.sr_sae_id','LEFT')
            ->join('up_u_user u1','sae.sae_send_uid=u1.user_id','LEFT')
            ->join('up_u_user u2','sr.sr_user_id=u2.user_id','LEFT')
            ->join('up_company_product cp','sae.sae_cp_id=cp.cp_id','LEFT')
            ->where($where)
            ->order('sr_time desc')
            ->page($page,10)
            ->field($field)
            ->select();
        if($data){
            $data = $this->foreachStrArr($data,'sr_imgs','sr_read_uid',$user_id,'up_sae_reply','sr_id','sae_zhuan_ids');
        }
        return json(['status'=>200,'msg'=>$data]);
    }
//    ----------------------------------系-统-消-息-------------------------------------

    /**
     * 获取所有和我有关的消息
     * type：1是系统消息 2会议提醒  3拜访提醒 4资料提醒（业务员才有资料提醒）
     * @return string
     */
    public function getNotice(){
        extract(input());
        if($type == 1) {
            $user = $this->getUserInfo($user_id,'user_type,user_time',2);
            $time = $user['user_time'];
            $user_type = $user['user_type']+1;
            $where_1 = [
                'n_type' => 1,
                'n_range' => ['in',"1,$user_type"],
                'n_del_user_id' => ['not like',"%,$user_id,%"],
            ];
            $where_2 = [
                'n_type' => 1,
                'n_range' => 4,
                'n_user_id' => ['like',"%,$user_id,%"],
                'n_del_user_id' => ['not like',"%,$user_id,%"],
            ];
            if(isset($keyword) && $keyword){
                $where_1['n_content'] = ['like',"%$keyword%"];
                $where_2['n_content'] = ['like',"%$keyword%"];
            }
            $data = Db::table('up_notice')
                ->where(function ($query) use ($where_1) {
                    $query->where($where_1);
                })
                ->whereOr(function ($query) use ($where_2) {
                    $query->where($where_2);
                })
                ->field('n_id,n_title,n_content,n_read_user_id,n_range,n_send_datetime,n_type')
                ->order('n_send_datetime DESC')
                ->page($page, 20)
                ->select();
            if($data){
                $data = $this->foreachStrArr($data,'','n_read_user_id',$user_id,'up_notice','n_id','');
            }
        }else{
            $field = 'n_id,n_title,n_content,n_read_user_id,n_read_user_id haveread,n_send_datetime,n_type,n_app_id';
            if($type == 2){
                $field .= ',m_id,m_name,m_type,m_start,m_end,m_day,m_week,m_address';
                $table = 'up_meeting';
                $join_field = 'm_id';
            }else if($type == 3){
                $field .= ',v_id,v_type,v_start,v_end,v_day,v_week,v_address,v_remark';
                $table = 'up_visit';
                $join_field = 'v_id';
            }else{
                $table = 'up_company_product_data';
                $join_field = 'cpd_id';
            }
            $where = [
                'n_type' => $type,
                'n_user_id' => $user_id
            ];
            if(isset($keyword) && $keyword){
                $where['n_content'] = ['like',"%$keyword%"];
            }
            $data = Db::table('up_notice')->alias('n')
                ->join("$table t", "n.n_app_id=t.{$join_field}", 'LEFT')
                ->where($where)
                ->field($field)
                ->order('n_send_datetime DESC')
                ->page($page, 20)
                ->select();
            if($data){
                foreach ($data as $k => $v){
                    if($v['n_read_user_id'] == 1){
                        Db::table('up_notice')->where('n_id', $v['n_id'])->setField('n_read_user_id',2);
                    }
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 消息详情
     */
    public function getNoticeInfo(){
        extract(input());
        $notice = Db::table('up_notice')
            ->where('n_id',$n_id)
            ->find();
        return json(['status'=>200,'msg'=>$notice]);
    }

    /**
     * 删除系统消息：单/多个删除
     * type：1 系统消息  2 拜访消息  3 提问消息  4 sae消息
     * @return string
     */
    public function deleteNoticeByIds()
    {
        extract(input());
        $n_id = trim($n_id,',');
        if($type == 1){
            $notice = Db::table('up_notice')
                ->where('n_id','in',$n_id)
                ->field('n_type,n_range,n_del_user_id,n_id')
                ->select();
            foreach ($notice as $k=>$v){
                if($v['n_type'] == 1){
                    $uids = $v['n_del_user_id'] . $user_id . ',';
                    $res = Db::table('up_notice')
                        ->where('n_id', $v['n_id'])
                        ->setField('n_del_user_id',$uids);
                }else{
                    $res = Db::table('up_notice')
                        ->where('n_id',$v['n_id'])
                        ->delete();
                }
            }
        }else{
            if($type == 2){
                $table = 'up_visit';
                $id_field = 'v_id';
                $del_field = 'v_del_uids';
            }elseif ($type == 3){
                $table = 'up_company_pd_question_reply';
                $id_field = 'dqr_id';
                $del_field = 'dqr_del_uid';
            }else{
                $table = 'up_sae_reply';
                $id_field = 'sr_id';
                $del_field = 'sr_del_uid';
            }
            $notice = Db::table($table)
                ->where($id_field,'in',$n_id)
                ->field("$id_field,$del_field")
                ->select();
            foreach ($notice as $k=>$v){
                $uids = $v[$del_field] . $user_id . ',';
                $res = Db::table($table)
                    ->where($id_field, $v[$id_field])
                    ->setField($del_field,$uids);
            }
        }
        if($res){
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>0,'msg'=>'操作失败']);
        }
    }

}